package com.web.ShoppingDemo.serviceImpl;


import java.util.List;

import org.springframework.stereotype.Service;

import com.web.ShoppingDemo.model.Forder;
import com.web.ShoppingDemo.model.Product;
import com.web.ShoppingDemo.model.Sorder;
import com.web.ShoppingDemo.service.SorderService;

@Service("sorderService")
public class SorderServiceImpl extends BaseServiceImpl<Sorder> implements
		SorderService {

	@Override
	public Sorder productToSorder(Product product) {
		Sorder sorder = new Sorder();
		sorder.setName(product.getName());
		sorder.setNumber(1);
		sorder.setPrice(product.getPrice());
		sorder.setProduct(product);
		return sorder;
	}

	@Override
	public Forder addSorder(Forder forder, Product product) {
		boolean isHave = false;
		Sorder sorder = this.productToSorder(product);
		for(Sorder old:forder.getSorderList()){
			//如果商品相同则将订单中的商品的数量进行改变
			if(old.getProduct().getId()==sorder.getProduct().getId()){
				old.setNumber(old.getNumber()+sorder.getNumber());
				isHave = true;
				break;
			}
		}
		if(!isHave){
			//建立购物车与购物项之间的关联
			sorder.setForder(forder);
			forder.getSorderList().add(sorder);
		}
		return forder;
	}

	@Override
	public Forder deleteSorder(Forder forder, Integer id) {
		Sorder sorder = null;
		
		for(Sorder old:forder.getSorderList()){
			if(id.equals(old.getProduct().getId())){
				sorder = old;
			}
		}
		forder.getSorderList().remove(sorder);
		return forder;
	}

	@Override
	public Forder updateSorder(Sorder sorder, Forder forder) {
		for(Sorder temp:forder.getSorderList()){
			if(temp.getProduct().getId().equals(sorder.getProduct().getId())){
				temp.setNumber(sorder.getNumber());
			}
		}
		return forder;
	}

	@Override
	public List<Object> querySale(int number) {
		return sorderDao.querySale(number);
	}

}
